package com.darksides.lendit.resource;

import static com.darksides.lendit.Constants.RegExp.REGEXP_USER_ID;

import java.util.logging.Logger;

import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.xml.bind.JAXBElement;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

import com.darksides.lendit.exceptions.EmailAlreadyUsedException;
import com.darksides.lendit.exceptions.UserNotFoundException;
import com.darksides.lendit.manager.UserManager;
import com.darksides.lendit.resource.model.User;
import com.sun.jersey.api.NotFoundException;

@Path("/user")
@Produces(MediaType.APPLICATION_XML) // "text/plain" ou "text/xml"(MediaType.TEXT_XML)
@Controller 
public class UserResource {

	private static final Logger log = Logger.getLogger(UserResource.class.getName());
	
	@Autowired
	private UserManager userManager;
	
	public UserResource() {
		log.info("UserResource - constructor");
	}
	
	@GET
	@Path("/{id: "+REGEXP_USER_ID+"}")
	public User get(@PathParam("id") String userId) throws NotFoundException {
		
		User user = userManager.getUser(Long.valueOf(userId)); 
		if (user!=null) {
			return user;
		} else {
			throw new NotFoundException("User with id "+userId+" not found.");	
		}
		
	}
	
	@POST
	@Consumes(MediaType.APPLICATION_XML)
	public User update(JAXBElement<User> user) {
		return userManager.updateUser(user.getValue());
	}
	
	@DELETE
	@Path("/{id: "+REGEXP_USER_ID+"}")
	public User delete(@PathParam("id") String userId) throws UserNotFoundException {
		return userManager.deleteUser(Long.valueOf(userId));
	}
	
	@PUT
	@Consumes(MediaType.APPLICATION_XML)
	public User add(JAXBElement<User> user) throws EmailAlreadyUsedException {
		return userManager.createUser(user.getValue());
	}
	
	/********************************************************/
	
	@GET
	@Path("/init")
	public User init() throws EmailAlreadyUsedException {
		
		User newUser = new User();
		newUser.setEmail("james.bond@gmail.com");
		newUser.setFirstName("James");
		newUser.setLastName("Bond");
		return userManager.createUser(newUser);
		
	}
	
	
}
